package cn.pconline.autoclub.service;

import java.util.List;

import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;

import cn.pconline.autoclub.entity.Area;

/**
 * 地区service
 * @author zhoutianhuai
 *
 */
public class AreaService {

    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private GeliDao geliDao;    
    private static final Logger log = LoggerFactory.getLogger(AreaService.class);

	/**
	 * 根据id查找地区
	 * @param id
	 * @return
	 */
	public Area findAreaById(long id){
		try{
			return geliDao.find(Area.class, id );
		}catch (EmptyResultDataAccessException e) {
			log.info("can't find Area in database which id is {}",id);
		}
		return null;
	}
		
	/**
	 * 根据大写字母查找城市列表
	 * @param initial 名称大写首字母
	 * @param areaLevel 城市级别
	 * @return
	 */
	public List<Area> listAreaByInitial(String initial, long areaLevel){
		SqlBuilder sql = new SqlBuilder();
		sql.appendSql("select id from ").appendSql(geliOrm.getTableName(Area.class))
			.appendSql(" where area_level = ").appendValue(areaLevel)
			.appendSql(" and initial = ").appendValue(initial)
			.appendSql(" order by area_code");
		return geliDao.list(Area.class, sql.getSql(), sql.getValues());
	}
	
	/**
	 * 查找热门城市
	 * @param initial 名称大写首字母
	 * @param areaLevel 城市级别
	 * @return
	 */
	public List<Area> listHotArea(){
		SqlBuilder sql = new SqlBuilder();
		sql.appendSql("select id from ").appendSql(geliOrm.getTableName(Area.class))
			.appendSql(" where is_hot = ").appendValue(Area.HOT_YES)
			.appendSql(" order by area_code");
		try {
			return geliDao.list(Area.class, sql.getSql(), sql.getValues());
        }
        catch(EmptyResultDataAccessException e ) {
        	return null;
        }
	
	}
	
	/**
	 * 根据地区代码获得地区
	 * @param areaCode 地区代码
	 * @return
	 */
	public Area findAreaByAreaCode(long areaCode){
		SqlBuilder sql = new SqlBuilder();
		sql.appendSql("select id from ").appendSql(geliOrm.getTableName(Area.class))
			.appendSql(" where area_code = ").appendValue(areaCode);
		try {
			List<Area>  areas = geliDao.list(Area.class, sql.getSql(), sql.getValues());
			if(areas != null && areas.size() == 1){
				return areas.get(0);
			}
			return null;
        }
        catch(EmptyResultDataAccessException e ) {
        	return null;
        }
		
	}
}
